import areaData from "@/components/_utils/area-json.js";
/* eslint-disable no-nested-ternary */
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
/**
 * num 小于0，左缩进num*2个空格； 大于0，右缩进num*2个空格。
 * @param {string} str 代码
 * @param {number} num 缩进次数
 * @param {number} len 【可选】缩进单位，空格数
 */
export function indent(str, num, len = 2) {
  if (num === 0) return str;
  const isLeft = num < 0;
  const result = [];
  let reg;
  let spaces = "";
  if (isLeft) {
    num *= -1;
    reg = new RegExp(`(^\\s{0,${num * len}})`, "g");
  } else {
    for (let i = 0; i < num * len; i++) spaces += " ";
  }

  str.split("\n").forEach((line) => {
    line = isLeft ? line.replace(reg, "") : spaces + line;
    result.push(line);
  });
  return result.join("\n");
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 下划转驼峰
// export function camelCase(str) {
// 	console.log(str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase()))
//   return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
// }

export function camelCase(name) {
  return name.replace(/\_(\w)/g, function(all, letter) {
    return letter.toUpperCase();
  });
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

export const exportDefault = "export default ";

export const beautifierConf = {
  html: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "separate",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
  js: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "normal",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
};

function stringify(obj) {
  return JSON.stringify(obj, (key, val) => {
    if (typeof val === "function") {
      return `${val}`;
    }
    return val;
  });
}

function parse(str) {
  JSON.parse(str, (k, v) => {
    if (v.indexOf && v.indexOf("function") > -1) {
      return eval(`(${v})`);
    }
    return v;
  });
}

export function jsonClone(obj) {
  return parse(stringify(obj));
}

// 深拷贝对象
export function deepClone(obj) {
  const _toString = Object.prototype.toString;

  // null, undefined, non-object, function
  if (!obj || typeof obj !== "object") {
    return obj;
  }

  // DOM Node
  if (obj.nodeType && "cloneNode" in obj) {
    return obj.cloneNode(true);
  }

  // Date
  if (_toString.call(obj) === "[object Date]") {
    return new Date(obj.getTime());
  }

  // RegExp
  if (_toString.call(obj) === "[object RegExp]") {
    const flags = [];
    if (obj.global) {
      flags.push("g");
    }
    if (obj.multiline) {
      flags.push("m");
    }
    if (obj.ignoreCase) {
      flags.push("i");
    }

    return new RegExp(obj.source, flags.join(""));
  }

  const result = Array.isArray(obj)
    ? []
    : obj.constructor
    ? new obj.constructor()
    : {};

  for (const key in obj) {
    result[key] = deepClone(obj[key]);
  }

  return result;
}

/**
 * 函数防抖
 * @param {Function} func
 * @param {number} delay
 * @param {boolean} immediate
 * @return {*}
 */

export function debounce(func, delay, immediate = false) {
  let timer,
    context = this;
  return (...args) => {
    if (immediate) {
      func.apply(context, args);
      immediate = false;
      return;
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

/**
 *
 * @description 根据key值，查询当前节点数据
 * @author 翟磊
 * @date 2022-03-23
 * @param {string} key - 目标值
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {string | number} 函数返回值:父节点
 *
 * */
export function getNodeByKey(key, keyName, data, children = "child") {
  let node;
  try {
    getData(data);

    function getData(data) {
      data.forEach((v, i) => {
        if (key == v[keyName]) {
          node = v;
          throw v;
        }
        if (v[children] && Array.isArray(v[children])) {
          getData(v[children]);
        }
      });
    }
  } catch (e) {
    return e;
  } finally {
    // !node && console.warn("查无此节点，请检查key值是否正确");
  }
}

/**
 *
 * @description 为节点添加自定义属性
 * @author 翟磊
 * @date 2022-03-23
 * @param {string} key - 目标值-传null，全级添加
 * @param {string} attName - 属性名
 * @param {string} value - 属性值
 * @param {[tree]} data - 树形数据源
 * */
export function addAttributeByKey(
  key,
  attName,
  value = null,
  data,
  children = "child"
) {
  try {
    if (key) {
      let itemNode = getNodeByKey(key, data);
      itemNode[attName] = value;
    } else {
      getData(data);
      function getData(data) {
        data.forEach((v) => {
          v[attName] = value;
          if (v.hasOwnProperty("disabled")) {
            v.disabled = v.disabled == 0 ? false : true;
          }
          if (v[children] && Array.isArray(v[children])) {
            getData(v[children]);
          }
        });
      }
    }
    throw data;
  } catch (e) {
    return e;
  }
}

/*
 * 当type=1时获取出生日期,type=2时获取性别,type=3时获取年龄
 * */
export function parseCardInfo(IdCard, type) {
  if (!isCardID(IdCard)) {
    console.warn("身份证号错误");
    return "";
  }
  if (type === 1) {
    //获取出生日期
    let birthday =
      IdCard.substring(6, 10) +
      "-" +
      IdCard.substring(10, 12) +
      "-" +
      IdCard.substring(12, 14);
    return birthday;
  }
  if (type === 2) {
    //获取性别
    if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
      return "UserSex.01";
    } else {
      return "UserSex.02";
    }
  }
  if (type === 3) {
    //获取年龄
    var ageDate = new Date();
    var month = ageDate.getMonth() + 1;
    var day = ageDate.getDate();
    var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1;
    if (
      IdCard.substring(10, 12) < month ||
      (IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day)
    ) {
      age++;
    }
    if (age <= 0) {
      age = 1;
    }
    return age;
  }

  //籍贯
  if (type == 4) {
    //省份
    let provinceNo = IdCard.substr(0, 2);
    let provinceName = getNodeByKey(
      provinceNo + "0000",
      "code",
      areaData,
      "children"
    )?.name;
    //市
    let cityNo = IdCard.substr(2, 2);
    let cityName = getNodeByKey(
      provinceNo + cityNo + "00",
      "code",
      areaData,
      "children"
    )?.name;
    //区
    let areaNo = IdCard.substr(4, 2);
    let areaName = getNodeByKey(
      provinceNo + cityNo + areaNo,
      "code",
      areaData,
      "children"
    )?.name;
    return [
      { code: provinceNo, name: provinceName },
      { code: provinceNo + cityNo + "00", name: cityName },
      { code: provinceNo + cityNo + areaNo, name: areaName },
    ];
  }
}

export function isCardID(sId) {
  let iSum = 0;
  let aCity = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外",
  };
  // 你输入的身份证长度或格式错误
  if (!/^\d{17}(\d|x)$/i.test(sId)) return false;
  sId = sId.replace(/x$/i, "a");
  //你的身份证地区非法
  if (aCity[parseInt(sId.substr(0, 2))] == null) return false;
  let sBirthday =
    sId.substr(6, 4) +
    "-" +
    Number(sId.substr(10, 2)) +
    "-" +
    Number(sId.substr(12, 2));
  let d = new Date(sBirthday.replace(/-/g, "/"));
  //身份证上的出生日期非法
  if (
    sBirthday !=
    d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
  )
    return false;
  for (let i = 17; i >= 0; i--)
    iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
  //你输入的身份证号非法
  if (iSum % 11 != 1) return false;
  return true;
}
